package com.itheima.web;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.R;
import com.itheima.dto.SubDto;
import com.itheima.exception.CustomException;
import com.itheima.service.ShoppingCartService;
import com.itheima.utils.BaseContext;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart cart = shoppingCartService.add(shoppingCart);
        return R.success(cart);
    }


    /**
     * 获取购物车数据
     *
     * @return
     */
    @GetMapping("/list")
    public R list() {
        List<ShoppingCart> list = shoppingCartService.findByUid(BaseContext.getCurrentId());
        return R.success(list);
    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R clean() {
        int row = shoppingCartService.clean(BaseContext.getCurrentId());
        if (row > 0) {
            return R.success("清空购物车成功！");
        } else {
            return R.error("清空购物车失败！");
        }
    }

    /**
     * 购物车删除
     */
    @PostMapping("/sub")
    public R sub(@RequestBody SubDto subDto) {
        if (ObjectUtils.isEmpty(subDto) || (StringUtils.isEmpty(subDto.getDishId()) && StringUtils.isEmpty(subDto.getSetmealId()))) {
            throw new CustomException("传入菜品id或套餐id为空");
        }
        List<ShoppingCart> shoppingCart = shoppingCartService.sub(subDto);
        return R.success(shoppingCart);

    }
}
